package com.cn.shiro_jwt_redis.service.impl;

import com.cn.shiro_jwt_redis.comm.model.ResultData;
import com.cn.shiro_jwt_redis.comm.utils.JWTUtil;
import com.cn.shiro_jwt_redis.comm.utils.JwtToken;
import com.cn.shiro_jwt_redis.comm.utils.RedisUtil;
import com.cn.shiro_jwt_redis.mapper.LoginMapper;
import com.cn.shiro_jwt_redis.mapper.MenuMapper;
import com.cn.shiro_jwt_redis.pojo.Login;
import com.cn.shiro_jwt_redis.pojo.Menu;
import com.cn.shiro_jwt_redis.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 张坤鹏
 * @Date: 2021/08/04/10:20
 * @Description:
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private  RedisUtil redisUtil;

    @Override
    @Transactional
    public ResultData login(Login login, HttpServletResponse response) {
        Login login1 = loginMapper.login(login);
        if (login1 != null) {
            List<Menu> list = menuMapper.getRoot(login1.getLoginId());
            for (Menu menu : list) {
                List<Menu> list1 = menuMapper.getChildren(login1.getLoginId(), menu.getMenuId());
                menu.setMenuChildren(list1);
            }
            Long currentTime=System.currentTimeMillis();
            String token= JWTUtil.sign(login.getUsername(),currentTime);
            System.out.println(token);
            redisUtil.set(login.getUsername(),currentTime,JWTUtil.REFRESH_EXPIRE_TIME);
            response.setHeader("token",token);
            response.setHeader("Access-Control-Expose-Headers", "Authorization");
            return ResultData.ok().data(list);
        }
        return ResultData.error();
    }
}
